package com.example.mydatabaseapp;

import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Random;

import com.example.mydatabaseapp.data.domain.ShaftPosition;
import com.example.mydatabaseapp.data.infrastructure.repository.ShaftPositionRepository;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
	private ShaftPositionRepository shaftPositionRepository;
	private Random randomizer;

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_query:
			Toast.makeText(this, "action_query", Toast.LENGTH_SHORT).show();
			showData();
			return true;

		case R.id.action_add:
			Toast.makeText(this, "action_add", Toast.LENGTH_SHORT).show();
			Integer number = (int) (this.randomizer.nextDouble() * 100.0);
					
			shaftPositionRepository.add(new ShaftPosition(number.toString(),"PO" + number.toString(), "0.0", "0.0"));
			showData();
			return true;
			
		case R.id.action_drop:
			Toast.makeText(this, "action_drop", Toast.LENGTH_SHORT).show();
			shaftPositionRepository.Drop();
			return true;
		}

		return false;
	}

	private void showData() {
		TextView logger = (TextView)findViewById(R.id.logger);
		logger.setText("");
		
		List<ShaftPosition> items = shaftPositionRepository.findAll();
		StringBuilder builder = new StringBuilder();
		for (ShaftPosition shaftPosition : items) {
			builder.append(shaftPosition.toString()+"\n");				
		}
		logger.setText(builder.toString());
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		
		//do initialization
		intialize();
		intializeDB();
	}

	private void intialize() {
		this.randomizer = new Random();
	}

	private void intializeDB() {
		this.shaftPositionRepository = new ShaftPositionRepository(this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}
